package com.assess.web.util;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {


    public static String format(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    public static String format(Date date) {
        return format(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getNow(String formatStr) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sf = new SimpleDateFormat(formatStr);
        String str = sf.format(calendar.getTime());
        return str;
	}
	
	public static Date parse(String date,String pattern) {
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		try {
			return format.parse(date);
		} catch (ParseException e) {
			throw new RuntimeException(e.getMessage(),e);
		}
	}


	public static Date parse(String date) {
		return parse(date,"yyyy-MM-dd HH:mm:ss");
	}

    /**
     * time 转为时长
     *
     * @param time
     * @return
     */
    public static String formatTime(Long time) {
        if (time == null) {
            return null;
        }else{
        	
            long hour = time/(60*60);
            long minute = (time - hour*60*60)/60;
            long second = time - hour*60*60 - minute*60;
            return (hour==0?"00":(hour>10?hour:("0"+hour)))+":"+(minute==0?"00":(minute>10?minute:("0"+minute)))+":"+(second==0?"00":(second>10?second:("0"+second)));
        }
    }

    /**
     * 当前时间增加天数
     *
     * @param addTime
     * @return
     */
    public static Date addTime(Integer addTime) {
        Calendar curr = Calendar.getInstance();
        curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + addTime);
        return curr.getTime();
    }
    
    /**
     * 固定时间增加天数
     * @param addTime
     * @return
     */
    public static Date addTime(Date date,Integer addTime) {
        Calendar curr = Calendar.getInstance();
        curr.setTime(date);
        curr.add(Calendar.DATE, addTime);
        return curr.getTime();
    }
    
    /**
     * 计算两个日期相差天数
     * @param date1
     * @param date2
     * @return
     */
    public static Double days(Date date1,Date date2){
    	 int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
    	 int hours = (int) ((date2.getTime() - date1.getTime()) % (1000*3600*24) / (1000*3600));
    	 Double hour = (new BigDecimal(hours).divide(new BigDecimal(24), 0, BigDecimal.ROUND_UP)).doubleValue();
         return new Double(days)+ hour;
    }
    
   
    

}
